import Vue from 'vue';
import axios from 'axios';
import qs from 'qs';

let cookie="";
axios.defaults.withCredentials = true; // 允许携带cookie
axios.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    var settle = require('axios/lib/core/settle');
    var buildURL = require('axios/lib/helpers/buildURL');
	console.log('axios adapter config: ',JSON.stringify(config));
	let url = ""
	/* #ifdef H5 */
	url = config.url;
	/* #endif */
	/* #ifndef H5 */
	url = new RegExp('^http(s)?://').test(config.url) ? config.url : config.baseURL + config.url // 判断时相对路径还是绝对路径，相对路径添加config.baseURL
	/* #endif */
    
    console.log('result.url: ',url);
	uni.request({
      method: config.method.toUpperCase(),
      url: buildURL(url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete (response) {
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config
        };
        settle(resolve, reject, response);
      }
    })
  })
}

// axios.defaults.baseURL = 'http://10.133.17.56:11008';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

export default function http(options){
    return new Promise((resolve, reject) => {
        // instance创建一个axios实例，可以自定义配置，可在 axios文档中查看详情
        const instance = axios.create({
            // 所有的请求都会带上这些配置，比如全局都要用的身份信息等。
            method: "post",
			/* #ifndef H5 */
			baseURL: 'http://10.133.17.56:11008', //H5不用这个，用代理
			/* #endif */
            headers: {
              "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            },
            credentials :"include",
			
            withCredentials:true,//允许跨域域名设置cookie
            timeout:30 * 1000 // 30秒超时
        });
        // http request 拦截器
        instance.interceptors.request.use(config => {
			console.log('请求拦截:',JSON.stringify(config));
			/* #ifndef H5 */
			if (cookie.length) {
			     config.headers.Cookie = cookie;
			}
			/* #endif */
            if ((config.method).toLowerCase() === 'post') {
                config.data = qs.stringify(config.data, {arrayFormat: 'brackets'})
            }else if((config.method).toLowerCase() === 'get'){
				config.params={
					timestamp:new Date().getTime(),//时间戳
					...config.data
				}
            }

            return config;
        });
        // http response 拦截器  与后台提前定义正确code 错误的提示
        instance.interceptors.response.use(
            response => {
				console.log('响应拦截:', response.status,',data: ',JSON.stringify(response));
				let cook = response.header['Set-Cookie'];
				if (cook && cook.length) {
					cookie = cook;
				}
				console.log('响应cookie: ',response.header['Set-Cookie']);
				if (response.status === 200) {
                    if(response.data.result == "noauth"){
                        // 清除登陆信息
                       
                        // return Promise.reject(response);
						return false;
                    } else if (response.data.result == 'success'){
						return resolve(response);
					} else {
						console.log("响应错误:",response.data);
						return reject(response);
					}
                } else {
                    return reject(response);
                }
            },
            error => {
                console.log("响应拦截错误:", error);
                if(error.message.includes('timeout')){   // 判断请求异常信息中是否含有超时timeout字符串
                
                    return reject(error);          // reject这个错误信息
                }
                if (error.response) {
                    if(error.response.status >= 400){//服务器、客户端错误处理
         
                    }
                  
                }
                return reject(error)
            }
        );

        instance(options).then(response => {
            // 把请求到的数据发到引用请求的地方
			console.log("======");
			
            resolve(response);
        }).catch(error => {
			console.log("++++++");
            // 错误日志处理
            // console.log("fetch.js => 请求异常信息："+JSON.stringify(error));
            //关闭load加载提示
            // vm.$loading.hide();
            reject(error);
        }).finally(() => {
            // console.log("finally");
        });
    });
}

export function POST(url, params) {
	let options = {
        url: url,
        method: 'post',
        data: params,
	}
	
	return http(options);
}

/* return Promise*/
export function GET(url, params) {
	let options = {
	    url: url,
	    method: 'get',
	    data: params,
	}
	return http(options);
}
